import math
import time
from random import randint, random
from model import *
from model.monster import Monster
from model.character import Character
import os
from common.fight import fight
import pickle


def print_delay(str_, second):
    print('----------------------------------------------------')
    print(str_)
    print('----------------------------------------------------')
    time.sleep(second)


def welcome():
    os.system('cls')
    print_delay('\033[0;30;47m 文字冒险岛v0.1\033[0m', 0.5)
    print_delay('\033[0;30;47m 作者：@Harry\033[0m', 0.5)
    print(
        '''\033[0;30;47m游戏简介：\033[0m
    打怪获得经验和金币，经验用于升级，普通战斗失败时可以用金币购买复活，修仙进阶战失败则直接结束游戏
    打怪会随机掉落技能，凑齐所有技能通关就很容易了，释放技能会获得技能经验，技能也可以升级，且无上限
    游戏在击杀怪物后会自动保存，下次游玩或者游戏失败时可以继续使用之前的角色
    可以在每次进入游戏时更换游戏模式
    之后会添加更多内容……
    回车键继续……
        ''')
    input()
    os.system('cls')


# 打包指令：pyinstaller -F main.py -c -n 文字冒险岛v0.1
if __name__ == '__main__':
    start_time = time.time()
    welcome()
    go_ahead_flag = False
    main_character = None
    user_rank = randint(400, 100000)

    # 初始化
    try:
        os.mkdir('db')
    except FileExistsError:
        print('存档文件夹已存在')
    else:
        print('存档文件夹创建成功')
    print('请勿删除或移动db文件夹，会导致存档消失')
    try:
        file_load = open('db/character.txt', 'rb')
    except FileNotFoundError:
        print("\033[0;34;40m创建新角色\033[0m")  # 蓝色
    else:
        history_character = pickle.load(file_load)
        file_load.close()
        if len(history_character.name) > 0:
            print('----------------------------------------------------')
            print("\033[0;34;40m发现游戏存档\033[0m")
            history_character.print_state()
            print('----------------------------------------------------')
            print("\033[0;34;40m是否继续？ Y：继续 其他：重新开始（存档会被清空）\033[0m")  # 蓝色
            is_go_head = input()
            if is_go_head.lower() == 'y':
                go_ahead_flag = True
                main_character = history_character
            else:
                go_ahead_flag = False

    # 是否继续游戏
    if go_ahead_flag is False:
        # 新角色流程
        print("\033[0;34;40m输入新角色名？ (回车确认)\033[0m")  # 蓝色
        main_character_name = input()
        if main_character_name == 'GM':
            main_character_name = 'GM'
        print("\033[0;34;40m选择阵营 ：（输入数字，回车确认，默认人族)\033[0m")  # 蓝色
        print('1. 人族：升级快，中期全能王，修仙最容易飞升', '\n2. 兽族：基础属性高，前期打架猛', '\n3. 暗夜精灵族： 天赋高，技能修炼效率提高50%，后期DPS')
        main_character_camp = input()
        if main_character_camp is '1':
            main_character_camp = '人族'
        elif main_character_camp is '2':
            main_character_camp = "兽族"
        elif main_character_camp is '3':
            main_character_camp = '暗夜精灵'
        else:
            main_character_camp = '人族'

        main_character = Character(main_character_name, main_character_camp)
        main_character.init()  # 初始化
        os.system('cls')
        print('----------------------------------------------------')
        print("\033[0;34;40m新角色创建成功！\033[0m")
        main_character.print_state()

    print("\033[0;34;40m请选择游戏模式：（输入数字，回车确认，默认快速模式)\033[0m")  # 蓝色
    print('1. 快速游戏 —— 快速体验游戏流程，游戏速度快')
    print('2. 修仙模式 —— 得道成仙，血肉飞升，游戏速度中等，打怪奖励提高 （推荐)')
    print('3. 无尽模式 —— 修炼无止尽，等级无上限，游戏速度慢 (摸鱼模式)')
    game_mode = input()
    if game_mode is '1':
        XiuXian_flag = False
        Hentai_flag = False
        game_speed = 0.5
        game_type = '快速游戏'
    elif game_mode is '2':
        XiuXian_flag = True
        Hentai_flag = False
        game_speed = 1
        game_type = '修仙模式'
    elif game_mode is '3':
        XiuXian_flag = False
        Hentai_flag = True
        game_speed = 2
        game_type = '无尽模式'
    else:
        XiuXian_flag = False
        Hentai_flag = False
        game_speed = 0.5
        game_type = '快速游戏'

    if main_character.name == 'GM':
        print_delay('GM模式:属性强化100倍，极快游戏速度，直接获得所有技能，降低升级所需经验', 1)
        game_type += '（GM特权）'
        game_speed = 0.1
        main_character.reinforcement_factor = 100
        for i in main_character.skills:
            i.is_learn = True

    while True:
        time.sleep(game_speed * 2)
        os.system('cls')
        max_num_monster = 23

        if random() < 0.8:
            # 随机小怪
            mons_name = '未知的怪物'
            ran_rank = randint(math.ceil(0.5 * main_character.rank), int(1.1 * main_character.rank))
            is_boss = False
            # 随机BOSS
            if random() > 0.9 and main_character.rank >= 50:
                is_boss = True
            rand_monster = Monster(mons_name, ran_rank, is_boss=is_boss)
        else:
            if main_character.rank < max_num_monster:
                max_num = main_character.rank
            else:
                max_num = max_num_monster
            rand_monster = eval('monster_' + str(randint(1, max_num)))
            # 减少低等级遇到BOSS几率
            rand_times = 100 / main_character.rank
            while rand_monster.is_boss and rand_times > 0:
                rand_times -= 1
                rand_monster = eval('monster_' + str(randint(1, max_num)))

        print('----------------------------------------------------')
        print("\033[5;34;46m{} {}正在战斗……      勇者排行：{}名\033[0m".format(game_type, main_character.name, user_rank))
        print('----------------------------------------------------')
        print('已经击败了' + str(main_character.defeat_monster_num) + '只怪物', '  金币：', main_character.gold, '  复活：',
              main_character.resurrection_times, '次')
        main_character.print_state()
        print('----------------------------------------------------')
        print('                         VS')
        rand_monster.print_state()

        if fight(main_character, rand_monster, XiuXian_flag, game_speed):
            main_character.defeat_monster_num += 1
        else:
            print_delay("\033[5;34;46m你战败了\033[0m", 1)
            if main_character.gold > main_character.rank * 500:
                main_character.blood_volume = main_character.rank * 500
                main_character.gold -= main_character.rank * 500
                print('花费' + str(main_character.rank * 500), '金币复活 你目前剩余：', main_character.gold, '金币')
                main_character.resurrection_times += 1
                print('回车键继续……')
                input()
            else:
                print_delay('需要' + str(main_character.rank * 500) + '金币复活,你只有' + str(main_character.gold), 5)
                break

        # 快速游戏——通关条件
        if Hentai_flag is not True:
            if main_character.rank >= 100 and not XiuXian_flag:
                os.system('cls')
                print("\033[0;34;40m即将迎来最后的决战！\033[0m")  # 蓝色
                monster_100.print_state()
                input('回车键继续……')
                if fight(main_character, monster_100, XiuXian_flag, game_speed):
                    print("\033[5;34;46m快速模式通关！！！\033[0m")
                else:
                    print("\033[5;34;46m再接再励！！！\033[0m")
                break
        # 修仙模式
        if XiuXian_flag is True:
            if 200 > main_character.rank >= 100 and main_character.state != '练气境':
                os.system('cls')
                print("\033[0;34;40m你的功力已经超越普通人，即将进入修仙阶段\033[0m")  # 蓝色
                monster_100.print_state()
                input('回车键继续……')
                if fight(main_character, monster_100, XiuXian_flag, game_speed):
                    os.system('cls')
                    print("\033[0;32;40m开始修仙……全属性*10， 你已经进入练气境\033[0m")
                    main_character.start_xiuxian()
                    main_character.reinforcement_factor += 2.0
                    main_character.print_state()
                    print('回车键继续……')
                    input()
                else:
                    print("\033[0;36;40m练气失败，天资不够,回车键继续……\033[0m")  # 青色

                    input()
                    break
                main_character.state = '练气境'

            if 300 > main_character.rank >= 200 and main_character.state != '先天境':
                main_character.reinforcement_factor += 3.0
                main_character.state = '先天境'
                print("\033[0;32;40m你已经进入{}\033[0m".format(main_character.state))
                print('回车键继续……')
                input()

            if 400 > main_character.rank >= 300 and main_character.state != '元婴境':
                main_character.reinforcement_factor += 4.5
                main_character.state = '元婴境'
                print("\033[0;32;40m你已经进入{}\033[0m".format(main_character.state))
                print('回车键继续……')
                input()

            if 500 > main_character.rank >= 400 and main_character.state != '金丹境':
                main_character.reinforcement_factor += 5.0
                main_character.state = '金丹境'
                print("\033[0;32;40m你已经进入{}\033[0m".format(main_character.state))
                print('回车键继续……')
                input()

            if 600 > main_character.rank >= 500 and main_character.state != '化神境':
                main_character.reinforcement_factor += 20.0
                main_character.state = '化神境'
                print("\033[0;32;40m你已经进入{}\033[0m".format(main_character.state))
                print('回车键继续……')
                input()

            if 700 > main_character.rank >= 600 and main_character.state != '返虚境':
                main_character.reinforcement_factor += 50.0
                main_character.state = '返虚境'
                print("\033[0;32;40m你已经进入{}\033[0m".format(main_character.state))
                print('回车键继续……')
                input()

            if 800 > main_character.rank >= 700 and main_character.state != '合道境':
                main_character.reinforcement_factor += 100.0
                main_character.state = '合道境'
                print("\033[0;32;40m你已经进入{}\033[0m".format(main_character.state))
                print('回车键继续……')
                input()

            if 900 > main_character.rank >= 800 and main_character.state != '渡劫境':
                main_character.reinforcement_factor += 233.0
                main_character.state = '渡劫境'
                print("\033[0;32;40m你已经进入{}\033[0m".format(main_character.state))
                print('回车键继续……')
                input()

            if main_character.rank >= 1000 and main_character.state != '大圆满':
                os.system('cls')
                print("\033[0;34;40m你的功力已经巅峰造极，击败最后的BOSS，即可飞升！\033[0m")  # 蓝色
                monster_1000.print_state()
                input('回车键继续……')
                if fight(main_character, monster_1000, XiuXian_flag, game_speed):
                    main_character.state = '大圆满'
                    print("\033[0;32;40m你已经进入{}\033[0m".format(main_character.state))
                    print('回车键继续……')
                    input()
                    print_delay('游戏通关！！！', 5)
                else:
                    print("\033[0;36;40m飞升失败，天资不够,回车键继续……\033[0m")  # 青色
                    print('回车键继续……')
                    input()
                break

        # 自动存档
        file_write = open('db/character.txt', 'wb')
        pickle.dump(main_character, file_write)
        file_write.close()
        print('----------------------------------------------------')
        print('当前战绩已保存 | Ctrl + C | 退出游戏')

    main_character.print_state()
    end_time = time.time()
    time_fen = math.floor((end_time - start_time) / 60)
    time_second = math.floor((end_time - start_time) % 60)
    print('----------------------------------------------------')
    print('已经击败了' + str(main_character.defeat_monster_num) + '只怪物', '金币：', main_character.gold, '复活：',
          main_character.resurrection_times, '次')
    print('----------------------------------------------------')
    print('游戏结束~  用时：', time_fen, '分钟', time_second, '秒')
    print('----------------------------------------------------')
    input()
